<?php

namespace backend\modules\supplier\models;

use Yii;

/**
 * 这个模型基于表 "{{%s_goods_class}}" 生成。
 *
 * @property integer $id
 * @property string $name
 * @property integer $parent_id
 * @property integer $sort
 */
class GoodsClass extends \common\models\AR {

    public $modelName = '商品分类';

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%s_goods_class}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['name', 'supplier_id'], 'required'],
            [['parent_id', 'sort', 'supplier_id'], 'integer'],
            [['name'], 'string', 'max' => 45],
            [['sort'], 'default', 'value' => 0]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '名称',
            'parent_id' => '父类目的ID，根类目默认为0',
            'sort' => '排序',
        ];
    }

    public function beforeValidate() {
        if (parent::beforeValidate()) {
            $this->supplier_id = Yii::$app->user->identity->supplier_id;
            return true;
        } else {
            return FALSE;
        }
    }

    public function getUsedCount() {
        //TODO 统计分类被引用的次数
        return 0;
    }

    /**
     * 获取分类树
     * @param type $pid
     * @return array
     */
    public static function getTree($pid = 0) {
        $ret = self::find()->where(['supplier_id' => Yii::$app->user->identity->supplier_id, 'parent_id' => $pid])->orderBy(['sort' => SORT_DESC])->asArray()->all();
        foreach ($ret as &$class) {
            $class['child'] = self::getTree($class['id']);
        }

        return $ret;
    }

    /**
     * 返回Ztree的数据格式
     * @param array $selectedIds 默认选中的ID
     * @return array
     */
    public static function getZtree($selectedIds = []) {
        $ret = [];
        $all = self::find()->where(['supplier_id' => Yii::$app->user->identity->supplier_id])->orderBy(['parent_id'=>SORT_ASC,'sort' => SORT_DESC])->asArray()->all();
        foreach ($all as $item) {
            $arr = ['id' => $item['id'], 'pId' => $item['parent_id'], 'name' => $item['name']];
            //in_array($item['id'], $selectedIds) && $arr['checked'] = true && $arr['open'] = true;

            $ret[] = $arr;
        }

        return $ret;
    }

}
